package com.example.teachermanagement.controller;

import com.example.teachermanagement.entity.Teacher;
import com.example.teachermanagement.repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.persistence.criteria.Predicate;

import java.util.*;

@RestController
@RequestMapping("/api/teachers")
public class TeacherController {
    
    private static final Logger logger = LoggerFactory.getLogger(TeacherController.class);

    @Autowired
    private TeacherRepository teacherRepository;

    // 获取所有教师，支持条件查询和分页
    @GetMapping
    public Map<String, Object> getAll(
            @RequestParam(required = false) String studentId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String major,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int limit) {
        
        try {
            // 创建查询条件
            Specification<Teacher> spec = (root, query, cb) -> {
                List<Predicate> predicates = new ArrayList<>();
                
                // 只有当参数不为null且不为空字符串时才添加查询条件
                if (studentId != null && !studentId.trim().isEmpty()) {
                    predicates.add(cb.like(root.get("studentId"), "%" + studentId.trim() + "%"));
                }
                if (name != null && !name.trim().isEmpty()) {
                    predicates.add(cb.like(root.get("name"), "%" + name.trim() + "%"));
                }
                if (major != null && !major.trim().isEmpty()) {
                    predicates.add(cb.like(root.get("major"), "%" + major.trim() + "%"));
                }
                
                // 如果没有查询条件，返回null（表示查询所有）
                return predicates.isEmpty() ? null : cb.and(predicates.toArray(new Predicate[0]));
            };

            // 创建分页对象（注意：page参数需要减1，因为Spring Data JPA的页码从0开始）
            Pageable pageable = PageRequest.of(page - 1, limit);
            
            // 执行分页查询
            Page<Teacher> teacherPage = teacherRepository.findAll(spec, pageable);
            
            // 构造返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("msg", "");
            result.put("count", teacherPage.getTotalElements());
            result.put("data", teacherPage.getContent());
            return result;
        } catch (Exception e) {
            logger.error("查询教师时发生错误: {}", e.getMessage(), e);
            return Map.of("code", 1, "msg", "查询失败：" + e.getMessage(), "count", 0, "data", Collections.emptyList());
        }
    }

    // 新增教师
    @PostMapping
    public Map<String, Object> create(@Valid @RequestBody Teacher teacher) {
        try {
            logger.info("接收到新增教师请求: {}", teacher);
            teacherRepository.save(teacher);
            logger.info("教师新增成功: {}", teacher);
            return Map.of("code", 0, "msg", "新增成功");
        } catch (DataIntegrityViolationException e) {
            logger.error("数据完整性错误: {}", e.getMessage(), e);
            return Map.of("code", 1, "msg", "保存失败：请确保所有必填字段都已填写");
        } catch (Exception e) {
            logger.error("新增教师时发生错误: {}", e.getMessage(), e);
            return Map.of("code", 1, "msg", "保存失败：" + e.getMessage());
        }
    }

    // 修改教师
    @PutMapping("/{id}")
    public Map<String, Object> update(@PathVariable Long id, @Valid @RequestBody Teacher teacher) {
        try {
            logger.info("接收到更新教师请求: id={}, teacher={}", id, teacher);
            teacher.setId(id);
            teacherRepository.save(teacher);
            logger.info("教师更新成功: {}", teacher);
            return Map.of("code", 0, "msg", "更新成功");
        } catch (DataIntegrityViolationException e) {
            logger.error("数据完整性错误: {}", e.getMessage(), e);
            return Map.of("code", 1, "msg", "更新失败：请确保所有必填字段都已填写");
        } catch (Exception e) {
            logger.error("更新教师时发生错误: {}", e.getMessage(), e);
            return Map.of("code", 1, "msg", "更新失败：" + e.getMessage());
        }
    }

    // 删除教师
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        try {
            logger.info("接收到删除教师请求: id={}", id);
            teacherRepository.deleteById(id);
            logger.info("教师删除成功: id={}", id);
            return Map.of("code", 0, "msg", "删除成功");
        } catch (Exception e) {
            logger.error("删除教师时发生错误: {}", e.getMessage(), e);
            return Map.of("code", 1, "msg", "删除失败：" + e.getMessage());
        }
    }
}
